# This file draws the plots for Loudness Paper 2

setwd("/Volumes/Data/localDataNoBackup/sfer9710/Development/smfrgsn-devel/Loudness2/CodeProcessing/PlotSubjectiveDataAgainstLoudness/")
library(lattice)
library(latticeExtra)
library(ggplot2)
library(ggExtra)

# Timeseries Loudness Graphs
#
# Load Loudness data (Full Timeseries)
ld = read.table("../LoudnessData.txt",header=TRUE,sep="\t")


levels(ld$File) <- c("Dvorak-Fwd","Bach-Prelude","Bjork-IOSQ","Dvorak-Rev","RLee-San'ya","ElliotS-SA")
levels(ld$Permutation) <- c("-3dB","0dB","6dB","12dB","24dB","Orig") 


p = ggplot(ld,aes(Time,SubjectiveData,grouping=Participant)) + geom_line(colour=alpha("black",1/10)) + facet_grid(File~Permutation) + theme_minimal() + ylim(0,100) + ylab("Subjective Loudness Response, arbitrary units") +xlab("Time (s)") + opts(panel.grid.major = theme_blank()) +opts(panel.grid.minor = theme_blank())
ggsave(p,file='SubjectiveData.pdf',width=12,height=8);


ld1= aggregate(cbind(SubjectiveData, LongTermLoudness) ~ Time+File+Permutation, data = ld, median)

levels(ld1$File) <- c("Dvorak-Fwd","Bach-Prelude","Bjork-IOSQ","Dvorak-Rev","RileyL-","ElliotS-SA")
levels(ld1$Permutation) <- c("-3dB","0dB","6dB","12dB","24dB","Orig") 


 loud <- xyplot(LongTermLoudness ~ Time | Permutation+File , data = ld1, type = "l",strip =        function(which.given,
                   which.panel,
                   factor.levels,
                   bg = trellis.par.get("strip.background")$col[which.given],
                   ...) {
              axis.line <- trellis.par.get("axis.line")
              pushViewport(viewport(clip = trellis.par.get("clip")$strip))
              if (which.given == 1)
              {
                  grid.rect(x = .26, just = "right",
                            gp = gpar(fill = bg, col = "transparent"))
                  ltext(factor.levels[which.panel[which.given]],
                        x = .24, y = .5, adj = 1)
              }
              if (which.given == 2)
              {
                  grid.rect(x = .26, just = "left",
                            gp = gpar(fill = bg, col = "transparent"))
                  ltext(factor.levels[which.panel[which.given]],
                        x = .28, y = .5, adj = 0)
              }
              upViewport()
          }, par.strip.text = list(lines = 0.4),ylab="Glasberg and Moore Loudness (sones)",xlab="Time (s)")
 subj <- xyplot(SubjectiveData ~ Time |  Permutation+File, data = ld1, type = "l",ylim=c(0,100), strip =
          function(which.given,
                   which.panel,
                   factor.levels,
                   bg = trellis.par.get("strip.background")$col[which.given],
                   ...) {
              axis.line <- trellis.par.get("axis.line")
              pushViewport(viewport(clip = trellis.par.get("clip")$strip))
              if (which.given == 1)
              {
                  grid.rect(x = .26, just = "right",
                            gp = gpar(fill = bg, col = "transparent"))
                  ltext(factor.levels[which.panel[which.given]],
                        x = .24, y = .5, adj = 1)
              }
              if (which.given == 2)
              {
                  grid.rect(x = .26, just = "left",
                            gp = gpar(fill = bg, col = "transparent"))
                  ltext(factor.levels[which.panel[which.given]],
                        x = .28, y = .5, adj = 0)
              }
              upViewport()
          }, par.strip.text = list(lines = 0.4),ylab="Subjective Loudness Response",xlab = "Time (s)")

pdf(file = "ObjectiveVSubjective.pdf",width =12,height = 8) 
 doubleYScale(loud, subj,style1=3,style2=4, add.ylab2 = TRUE)
dev.off()


# Plot against Familiarity

ld = read.table("../LoudnessData.txt",header=TRUE,sep="\t")
ld3=ld;
ld3$Familiar = ld3$Familiarity %in% c("Yes","HeardItSomewhere")  
ld3 = subset(ld3, PresOrder < 9)
ld4 = subset(ld3,Time==0)

ld3= aggregate(SubjectiveData ~ Time+File+Permutation+Familiar, data = ld3, median)
ld3$File = factor(ld3$File,levels= c("Dvorak-Fwd","Dvorak-Rev","ElliotS-SA","Bjork-IOSQ","RLee-San'ya","Bach-Prelude"))
ld3$Permutation = factor(ld3$Permutation,levels= c("-3dB","0dB","6dB","12dB","24dB","Orig") )

ld4.n = ddply(ld4, .(Permutation,File), function(val) table(val$Familiar))
ld4.n$str =  sprintf("%d Unfamiliar, %d Familiar",ld4.n[,3], ld4.n[,4])
ld4.n = melt(ld4.n, idvar=c("Permutation","File"))
names(ld4.n) = c( "Permutation", "File" , "str", "Familiar", "value")

p = ggplot(ld3,aes(Time,SubjectiveData,grouping=Familiar)) + geom_line(aes(colour=Familiar)) + facet_grid(File~Permutation) +xlab("Time(s)") + theme_minimal() + geom_text(data=ld4.n, aes(x=0,y=80,label=str,size=3,hjust=0,vjust=0), colour="grey",parse=FALSE) +ylim(0,100)

p



ggsave(p,file="FamiliarityComparison.pdf",width = 12,height = 8)


# Give Familiarity responses
ld3=ld;
ld3 = subset(ld3,Familiarity != "empty")
ld3 = droplevels(ld3)
ld3$Familiar = ld3$Familiarity %in% c("Yes","HeardItSomewhere","NotSure")  
ld3 = subset(ld3, PresOrder < 9)
ldFam = subset(ld3,Time==0)
fam = table(ldFam$Familiarity,ldFam$File)
fam = as.data.frame(fam)
fam$Var1 = factor(fam$Var1,levels=c("No","NotSure","HeardItSomewhere","Yes") )
ggplot(fam,aes(Var1,Freq)) +geom_bar()+facet_grid(~Var2)+opts(axis.text.x = theme_text(angle=90,hjust=1)) + xlab("Familiarity Response") + ylab("Response Frequency")







# Correlation Loudness Graph
#
# Load correlation data (Only Correlations)
# Some of the names for this dataset are incorrect
cor=read.table("../LoudnessCorr.txt",header=TRUE,sep="\t")

# Divide the Stimulus name into both permutation and stimulus 
cor$Permutation = substr(as.character(cor$File),6,6)
cor$Permutation = factor (cor$Permutation)
cor$Stimulus = substr(as.character(cor$File),1,5)
cor$Stimulus = factor (cor$Stimulus)
levels(cor$Stimulus) <- c("Dvorak-Fwd","Bach-Prelude","Bjork-IOSQ","Dvorak-Rev","RLee-San'ya","ElliotS-SA")
levels(cor$Permutation) <- c("-3dB","0dB","6dB","12dB","24dB","Orig") 

# Plot Correlation by Permutation, and Stimulus
loudCorPlot = ggplot(cor, aes(LagDLM/4,R.squaredDLM,shape=Stimulus))+geom_point() +facet_grid(Permutation ~.) + ylim(0,0.5) + xlim(0,2) + xlab("Lag time (s)") + ylab("Correlation values (R-squared)")
# Save Plot to PDF File
ggsave(loudCorPlot,file="LoudnessCorrelationPlot4HzFacetPermutationColourStimulus.pdf",width=5,height = 6)

